package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.pojo.vo.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",
        urlPatterns = {"/insertProduct.html","/insertBanner.html","/admin.html","/product/delete"})
public class MyFilter implements Filter {
    //过滤器初始化方法
    public void init(FilterConfig config) throws ServletException {
    }
    //过滤器销毁时执行的方法
    public void destroy() {
    }
    //请求资源之前和之后执行的方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //因为要用到子类类型中的方法 所以进行类型强转
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        //从请求对象中获取当前客户端对应的会话对象
        HttpSession session = req.getSession();
        //从会话对象中获取登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        if (user!=null){//登录过  放行允许客户端请求资源
            chain.doFilter(request, response); //请求资源
        }else{//未登录 禁止请求资源 并显示登录页面
            res.sendRedirect("/login.html");
        }
    }
}
